package basis;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;

/**
 * 大整数加法，乘法
 * 
 * @author 71936_000
 * 
 */
public class Demo8_BigNumber {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入第一个大整数");
		String p = sc.next();
		System.out.println("请输入第二个大整数");
		String q = sc.next();
		Demo8_BigNumber dg = new Demo8_BigNumber();
		System.out.println(p + "+" + q + "=" + dg.add(p, q));
		dg.multiply(p, q);
	}

	public String add(String m, String n) {

		char[] a = new StringBuffer(m).reverse().toString().toCharArray();
		char[] b = new StringBuffer(n).reverse().toString().toCharArray();
		int A = a.length;
		int B = b.length;
		int longLength;
		if (A > B) {
			longLength = A;
		} else {
			longLength = B;
		}
		int[] str = new int[longLength + 1]; // 结果最长的长度
		for (int i = 0; i <= longLength; i++) { // 将对应角标位置的书相加，然后存放到数组中去
			int aint = i < A ? (a[i] - '0') : 0;
			int bint = i < B ? (b[i] - '0') : 0;
			str[i] = aint + bint;
		}
		// 处理结果集合，如果大于10的就向前一位进位，本身进行除10取余
		for (int i = 0; i < str.length; i++) { // 判断相加之后的每一个角标对应的值是否大于10，并向后一位进位
			if (str[i] > 10) {
				str[i + 1] += str[i] / 10;
				str[i] %= 10;
			}
		}
		StringBuffer sb = new StringBuffer();
		boolean qianzhi = true; // 判断最改为是否为0，如果为0，则不进行保存，否则将最后结果由高到低进行保存并输出
		for (int i = longLength; i >= 0; i--) {
			if (str[i] == 0 && qianzhi) {
				continue;
			} else {
				qianzhi = false;
			}
			sb.append(str[i]);
		}
		return sb.toString();
	}

	// 乘法
	public static void multiply(String m, String n) {
		char signA = m.charAt(0);
		char signB = n.charAt(0);
		char[] a = new StringBuffer(m).reverse().toString().toCharArray();
		char[] b = new StringBuffer(n).reverse().toString().toCharArray();
		int A = a.length;
		int B = b.length;
		int longLength = A + B; // 结果最大长度
		int[] str = new int[longLength];
		for (int i = 0; i < A; i++) { // 每位数与上一位数的乘积
			for (int j = 0; j < B; j++) {
				str[i + j] += (int) (a[i] - '0') * (int) (b[j] - '0');
			}
		}
		for (int i = 1; i < str.length; i++) { // 结果相加并进位
			if (str[i] > 10) {
				str[i] += str[i] / 10;
				str[i] %= 10;
			}
		}
		StringBuffer sb = new StringBuffer();

		boolean qianzhi = true;
		for (int i = longLength - 1; i >= 0; i--) { // 判断字符串前面是否有0，如果有则不进行保存
			if (str[i] == 0 && qianzhi) {
				continue;
			} else {
				qianzhi = false;
			}
			sb.append(str[i]);
		}
		System.out.println(sb.toString());
	}
}
